class Product < ActiveRecord::Base

  #association
  belongs_to :National, :foreign_key => :national_id
	belongs_to :Farm, :foreign_key => :farm_id
  has_many :prices, :dependent => :destroy
  has_many :productorigins, :dependent=> :destroy
  belongs_to :commoncodes, :foreign_key => :product_type

  #validation
  validates_presence_of :name,
  :message => "상품 이름이 없습니다."
	validates_presence_of :desc1,
	:message => "상품 요약정보가 없습니다."
	validates_presence_of :desc2,
	:message => "상품 요약정보가 없습니다."

  # def's
	def self.find_products_for_sale
		find(:all, :order => "id")
	end

  def new_productorigin_attributes=(productorigin_attributes)
     productorigin_attributes.each do |productorigin|
      productorigins.build(productorigin)
    end
  end

  def new_price_attributes=(price_attributes)
    price_attributes.each do |price|
      prices.build(price)
    end
  end

  def existing_productorigin_attributes=(productorigin_attributes)
    productorigins.reject(&:new_record?).each do |productorigin|
       attributes = productorigin_attributes[productorigin.id.to_s]
       if attributes
         productorigin.attributes = attributes
       else
         productorigins.delete(productorigin)
       end
    end
  end


  def existing_price_attributes=(price_attributes)
    prices.reject(&:new_record?).each do |price|
       attributes = price_attributes[price.id.to_s]
       if attributes
         price.attributes = attributes
       else
         prices.delete(price)
       end
    end
  end


end

